<template>
  <div :class='s.wrap'>
    <action-bar :title='game.GAME_NAME' :style='{backgroundColor: "#e54f20"}'>
      <template slot='left'>
        <action-button @click='onBack' color='#fff'>
          <i class="iconfont icon-fanhui"></i>
        </action-button>
        <action-button color='transparent' v-if='showRule'></action-button>
      </template>
      <template slot='right'>
        <action-button @click='onRule' color='#fff' v-if='showRule'>
          <i class="iconfont icon-bisaiguize"/>
        </action-button>
        <action-button @click='onShare' color='#fff'>
          <i class="iconfont icon-fenxiang"/>
        </action-button>
      </template>
    </action-bar>
    <overview
      v-if='game.GAME_ID !== ""'
      :game='game'
      @registered='onRegistered'></overview>
    <new-msg v-if='game.GAME_STEP === "3"' 
      ref='newMsg'
      @click='onComment'></new-msg>
    <winner 
      :gameID='$route.query.gameId'
      :createUser='game.CREATE_USER'
      v-if='game.GAME_STEP === "4"'></winner>
    <div :class='s.totalProfit'>
      <div :class='s.right'></div>
      <div :class='s.mid'>
        <div :class='s.title'>总盈利榜</div>
        <img src='~assets/images/zongyinglibang@3x.png'>
      </div>
      <div :class='s.right'>
        <img src="~assets/images/toupiao@2x.png" @click='onVote'>
      </div>
    </div>
    <div :class="s.hint">注：已调仓成功的用户才能上榜哦～</div>
    <div :class='s.groupList'>
      <group-list
      ref='groupList'
      :gameDetail='game'
      :isAttend='registered'
      :isLoading='playersOptions.isFirstLoading'
      :showTotal='playersOptions.showTotal'
      :gameStep='playersOptions.gameStep'
      :rankList='playersOptions.rankList'
      @loadmore='onLoadPlayers'></group-list>
    </div>
    <img :src='pinglunqu' v-if='showSpeak' @click='onComment' :class="s.pinglunqu">
    <img :src='jingcai' v-else @click='onComment' :class="s.jingcai">
    <div :class='s.talk'>
      <speak ref='speak'
        :visible.sync='isInTalkTime'
        v-if='showSpeak'
        :class='s.speak'
        :options='speakOptions'
        @speaking='onNewMsg'></speak>
    </div>
  </div>
</template>

<script>
import ActionBar from 'components/actionBar'
import ActionButton from 'components/actionBar/ActionButton'
import Overview from 'components/game/detail/Overview'
import Winner from 'components/game/detail/Winner'
import GroupList from 'components/teamGame/GroupList'
import { getSessionGame, saveSessionGame } from 'components/game/openGame'
import LocalDAO from 'common/localDAO'
import RemoteDAO from 'common/remoteDAO'
import Constant from 'common/constant'
import filterGameStage from 'filters/filterGameStage'
import cutNumber from 'filters/cutNumber'
import Speak from 'components/game/comment/Speak'
import NewMsg from 'components/game/detail/NewMsg'
import CommonUtil from 'common/common.util'
export default {
  components: { ActionBar, ActionButton, Overview, Winner, GroupList, Speak, NewMsg },
  filters: {
    filterGameStage, cutNumber
  },
  data () {
    return {
      game: {
        CREATE_USER: '',
        GAME_STEP: '-1',
        GAME_STATUS: '', //审核状态
        GAME_TYPE: '',
        BEGIN_DATE: '',
        END_DATE: '',
        JOIN_BEGIN_DATE: '',
        GAME_ID: '',
        GAME_NAME: '',
        GAME_ATTEND_PERSON: '0',
        GAME_RULE: [] // [{"AWARD_RULE":4,"DESC":null}]
      },
      playersOptions: {
        isFirstLoading: true,
        isLoading: false,
        gameStep: -1,
        showTotal: true,
        rankList: [],
        pageSize: 20,
        pageNo: 1
      },
      registered: false,
      userCode: '',
      pinglunqu: require('assets/images/pinglunqu.png'),
      jingcai: require('assets/images/jingcai.png'),
      speakOptions: {
        userCode: '',
        userHead: '',
        nickName: '',
        objectType: 4,
        topicCode: '',
        topicName: '',
        style: '#f2f2f2'
      },
      isInTalkTime: true
    }
  },
  computed: {
    showRule: function () {
      if (this.game.GAME_ID === '201707270050005203' || this.game.GAME_NAME === '甜橙理财校园股神大赛第一季' || this.game.GAME_NAME === '甜橙理财校园股神大赛第二季') {
        return false
      }
      return true
    },
    showSpeak: function () {
      // console.warn('GAME_STEP', this.game.GAME_STEP)
      // console.warn('registered', this.registered)
      // console.warn('isInTalkTime', this.isInTalkTime)
      if (this.game.GAME_STEP === '3' && this.registered && this.isInTalkTime) return true
      return false
    }
  },
  mounted () {
    this.game.GAME_ID = this.$route.query.gameId
    var sGame = getSessionGame(this.game.GAME_ID)
    if (sGame !== null) {
      this.game = sGame
      this.speakOptions.topicName = this.game.GAME_NAME
      this.updateShareInfo()
    }
    this.userCode = LocalDAO.getUserCode()
    this.fetchGame(this.$route.query.gameId, this.userCode)
    this.TD('12001', this.userCode)
  },
  methods: {
    refreshData () {
      this.speakOptions.topicName = this.game.GAME_NAME
      this.speakOptions.userCode = this.userCode;
      this.speakOptions.nickName = LocalDAO.getNickname();
      this.speakOptions.userHead = LocalDAO.getUserHead();
      this.speakOptions.topicCode = this.game.GAME_ID
      this.playersOptions.gameStep = parseInt(this.game.GAME_STEP)
      this.onLoadPlayers()
    },
    onLoadPlayers () {
      if (this.playersOptions.gameStep === -1 ) {
        this.$refs.groupList.bottomLoaded()
        this.playersOptions.isLoading = false
        return
      }
      if (this.playersOptions.isLoading) return
      this.playersOptions.isLoading = true
      RemoteDAO.callHB003(
        this.userCode,
        this.game.GAME_ID,
        this.playersOptions.pageSize,
        this.playersOptions.pageNo,
        this.playersOptions.gameStep,
        resp => {
          if (resp.error !== '0') {
            this.$store.dispatch('setTip',{text:resp.data})
            this.$refs.groupList.bottomLoaded()
          } else {
            if (resp.data.body.length > 0) {
              this.playersOptions.rankList = this.playersOptions.rankList.concat(resp.data.body)
              this.$refs.groupList.bottomLoaded()
              this.$nextTick(() => {
                this.playersOptions.pageNo += 1
                this.updateSharePlayers(resp.data.body)
              })
            } else {//已全部加载
              this.$refs.groupList.bottomAllLoaded()
            }
          }
          this.playersOptions.isLoading = false
          this.playersOptions.isFirstLoading = false
        })
    },
    onNewMsg (msg) {
      msg.DEFAULT_HEAD_INDEX = 1
      msg.USER_CODE = this.userCode
      msg.USER_HEAD = LocalDAO.getUserHead()
      msg.NICKNAME = LocalDAO.getNickname()
      switch(msg.type){
        case 1: //emoji
          msg.COMMUNITY_CONTENT = '<img class="emoji_item" src="'+ msg.path +'" />';
          break;
        default:
          msg.COMMUNITY_CONTENT = msg.text;
      }
      this.$refs.newMsg.pushMsg(msg)
    },
    onComment () {
      this.$router.push({path: '/game/comment', query: {
        topicCode: this.game.GAME_ID, 
        topicName: this.game.GAME_NAME, 
        objectType: 4, 
        identity: this.registered ? Constant.game.identity.PLAYER : Constant.game.identity.ONLOOKER,
        gameStep: this.game.GAME_STEP
      }})
    },
    fetchGame (gameId, userCode) {
      var params = {
        userCode: userCode,
        gameId: gameId,
        gameStatus: '',
        gameKind: '',
        pageSize: '1',
        pageNum: '1',
        gameType: 'NETDS'
      }
      RemoteDAO.callUC12008302(params, resp => {
        if (resp.error !== '0') {
          this.$store.dispatch('setTip', {text: resp.data})
          return
        }
        if (resp.data.body.length > 0) {
          this.game = resp.data.body[0] || {}
          this.game.GAME_RULE = this.game.GAME_RULE === '' ? [] : JSON.parse(this.game.GAME_RULE)
          this.$nextTick(() => {
            this.updateShareInfo()
          })
          this.refreshData()
          saveSessionGame(this.game)
        }
      })
    },
    onRegistered (registered) {
      this.registered = registered
    },
    onBack () {
      if (typeof (this.$route.query.cleanStorage)!== 'undefined') window.location.href = 'gtjanormal://goback'
      else this.$router.go(-1)
    },
    onRule () {
      if (this.game.GAME_TYPE === 'CLS') {
        this.$router.push({path:'/game/rules', query: { kind: 'CLS'}})
      }
      else if (this.game.GAME_TYPE === 'JYS') {
        this.$router.push({path:'/game/rules', query: { kind: 'JYS'}})
      }
      else {
        if (this.game.GAME_RULE.length > 0 ){
          switch (this.game.GAME_RULE[0].AWARD_RULE) {
            case 1:
              this.$router.push({path:'/game/rules'})
              break
            case 2:
              this.$router.push({path:'/game/rules'})
              break
            case 3:
              this.$router.push({path:'/game/rules3'})
              break
            case 4:
              this.$router.push({path: '/game/rules4', query: {gameID: this.game.GAME_ID}})
              break
            default:
              this.$router.push({path:'/game/rules'})
          }
        } else this.$router.push({path:'/game/rules'})
      }
    },
    onShare () {
      var title = '无兄弟，不炒股'
      var content = "兄弟们在" + LocalDAO.getShareGameDetails().overview.gameName + "等你呢"
      var tdId = "1011"
      var icon = "http://dl.app.gtja.com/nrng/shareimages/bisaijinxing.png"
      RemoteDAO.sendShareData(Constant.storage.SHARE_GAME_DETAILS, data => {
        let url = 'http://dl.app.gtja.com/nrng/share/' + Constant.storage.SHARE_GAME_DETAILS + '.html?userCode=' + this.userCode + '&url=' + data
        RemoteDAO.share(title, content, url, 'title', icon)
      })
    },
    onVote () {
      if (this.game.GAME_STEP === '5') {
        this.$store.dispatch('setTip', {text:'比赛已失效'})
        return
      }
      if (LocalDAO.getNickname()) {
        this.$router.push({
          path: '/game/gamevote',
          query: {
            gameId: this.game.GAME_ID,
            gameStep: this.game.GAME_STEP,
            gameName: this.game.GAME_NAME,
            identity: this.registered ? Constant.game.identity.PLAYER : Constant.game.identity.ONLOOKER
          }
        })
      } else {
        RemoteDAO.callNativeLogin (resp => {
          if (resp.error === 0) {//跳转投票页
            this.$router.push({
              path: '/game/gamevote',
              query: {
                gameId: this.game.GAME_ID,
                gameStep: this.game.GAME_STEP,
                gameName: this.game.GAME_NAME,
                identity: this.registered ? Constant.game.identity.PLAYER : Constant.game.identity.ONLOOKER
              }
            })
          } else {
            this.$store.dispatch('setTip', {text:resp.data})
          }
        })
      }
    },
    updateSharePlayers(list) {
      var shareGameDetails = LocalDAO.getShareGameDetails() || {players: {list:[]}}
      if (!shareGameDetails.overview || !shareGameDetails.overview.gameId ) this.updateShareInfo()
      shareGameDetails.players.list = []
      var startRankNum = 1
      shareGameDetails.players.list = shareGameDetails.players.list.concat(list.map((item,index) => {
        let shareItem = {
          nickname: item.NICKNAME,
          userCode: item.USER_CODE,
          useGameAmount: CommonUtil.toFixed(item.USE_GAME_AMOUNT, 0),
          winWallet: CommonUtil.toFixed(item.WIN_WALLET, 0),
          ranknum: startRankNum,
          totalFloatprofit: CommonUtil.toFixed(item.total_floatprofit, 2) + "%",
          subscribePrice: CommonUtil.toFixed(item.SUBSCRIBE_PRICE, 0)
        }
        startRankNum = startRankNum + 1
        return shareItem
      }))
      shareGameDetails.players.pageNo = this.playersOptions.pageNo - 1
      shareGameDetails.players.pageSize = this.playersOptions.pageSize
      LocalDAO.setShareGameDetails(shareGameDetails)
    },
    updateShareInfo () {
      var shareGameDetails = LocalDAO.getShareGameDetails() || {}
      // if (shareGameDetails.ranking && shareGameDetails.ranking.gameId && shareGameDetails.ranking.gameId.length > 0) return
      shareGameDetails.ranking = {
        gameStage: filterGameStage(this.game.GAME_STEP),
        gameStep: this.game.GAME_STEP,
        identity: this.game.identity, 
        gameAttendPerson: this.game.GAME_ATTEND_PERSON,
        gameMaxLimit: this.game.GAME_MAX_LIMIT, 
        gameId: this.game.GAME_ID, 
        gameName: this.game.GAME_NAME
      }
      shareGameDetails.overview = {
        gameId: this.game.GAME_ID,
        gameStage: filterGameStage(this.game.GAME_STEP),
        identity: this.game.identity,
        gameAmount: cutNumber(this.game.GAME_AMOUNT),
        gameKind: this.game.GAME_KIND,
        gameType: this.game.GAME_TYPE,
        gameAttendPerson: this.game.GAME_ATTEND_PERSON,
        gameMaxLimit: this.game.GAME_MAX_LIMIT,
        gameName: this.game.GAME_NAME,
        currentUserCode: this.game.currentUserCode,
        gamePWD: this.game.GAME_PWD,
        beginDate: this.game.BEGIN_DATE,
        endDate: this.game.END_DATE,
        gameNeedAmount: parseInt(this.game.GAME_NEED_AMOUNT),
        createrCompany: this.game.CREATER_COMPANY,
        createrNickname: this.game.CREATER_NICKNAME,
        createrHead: this.game.CREATER_HEAD,
        isGamePWD: this.game.IS_GAMEPWD,
        createUser: this.game.CREATE_USER
      }
      shareGameDetails.players = shareGameDetails.overview
      shareGameDetails.players.list = []
      shareGameDetails.adDownload = {userCode: this.userCode};
      LocalDAO.setShareGameDetails(shareGameDetails);
    },
    TD(code,userCode){
      try{
        TDAPP.onEvent(code, "",  {"usercode":userCode});
        TDAPP.send();
      }catch(err){
        console.warn(err);
      }
    }
  }
}
</script>

<style lang="less" module='s'>
.wrap{
  background-color: #fbfbfc;
  .totalProfit{
    margin: 5px auto;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .mid{
      width: 40%;
      margin: auto 10px;
      position: relative;
      color: #fff;
      .title{
        position: absolute;
        top: 17px;
        width: 100%;
        text-align: center;
        font-size: 13px;
      }
      img{
        width: 100%;
      }
    }
    .right{
      flex: 1;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      img{
        width: 60%;
        margin: 0 10px;
      }
    }
  }
  .talk{
    position: fixed;
    z-index: 1001;
    width: 100%;
    bottom: 0px;
    text-align: right;
    .speak{
      text-align: left;
    }
  }
  .pinglunqu{
    position: fixed;
    z-index: 1001;
    width: 15%;
    right: 10px;
    bottom: 50px;
  }
  .jingcai{
    position: fixed;
    z-index: 1001;
    width: 15%;
    right: 10px;
    bottom: 50px;
  }
}
.hint{
  text-align: center;
  font-size: 12px;
  color: #f7743a;
  margin-top: 15px;
}
.groupList{
  min-height: 350px;
  background-color: #fff;
}
</style>